/**
   Copyright 2012 Shakil Siraj (shakil.siraj@gmail.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.googlecode.objectify.test.dataloader.example.bookstore.dao;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.cmd.Query;
import com.googlecode.objectify.test.dataloader.example.bookstore.PaymentType;
import com.googlecode.objectify.test.dataloader.example.bookstore.SaleRecord;

/**
 * @author Shakil Siraj (shakil.siraj@gmail.com)
 * 
 */
public class SaleRecordsDAO {

	private final int MAX_FETCH_SIZE = 100;

	public Integer getTotalNumberOfSaleRecords() {
		return ObjectifyService.ofy().load().type(SaleRecord.class).keys()
				.list().size();
	}

	public Double getTotalNumberOfSalesForPaymentTypeUsingFethcAll(
			final PaymentType paymentType, final Date startDate,
			final Date endDate) {

		Query<SaleRecord> saleRecordsQuery = ObjectifyService.ofy().load()
				.type(SaleRecord.class).filter("paymentType", paymentType)
				.filter("saleDate >= ", startDate)
				.filter("saleDate < ", endDate);

		double totalSales = 0;

		Iterable<SaleRecord> saleRecords = saleRecordsQuery.list();
		for (SaleRecord saleRecord : saleRecords) {
			totalSales += saleRecord.getTotalAmount();
		}

		return totalSales;

	}

	public Double getTotalNumberOfSalesForPaymentTypeUsingBatch(
			final PaymentType paymentType, final Date startDate,
			final Date endDate) {

		Query<SaleRecord> saleRecordsQuery = ObjectifyService.ofy().load()
				.type(SaleRecord.class).filter("paymentType", paymentType)
				.filter("saleDate >= ", startDate)
				.filter("saleDate < ", endDate);

		List<Key<SaleRecord>> saleRecordsKeys = saleRecordsQuery.keys().list();

		double totalSales = 0;
		int lastPosition = 0;

		while (true) {

			int endPosition = (lastPosition + MAX_FETCH_SIZE) > saleRecordsKeys
					.size() ? saleRecordsKeys.size() : lastPosition
					+ MAX_FETCH_SIZE;
			List<Key<SaleRecord>> saleRecordKeysBatch = saleRecordsKeys
					.subList(lastPosition, endPosition);

			Collection<SaleRecord> batchRecords = ObjectifyService.ofy().load()
					.keys(saleRecordKeysBatch).values();
			for (SaleRecord saleRecord : batchRecords) {
				totalSales += saleRecord.getTotalAmount();
			}

			lastPosition += MAX_FETCH_SIZE;
			if (lastPosition > saleRecordsKeys.size())
				break;
		}

		return totalSales;
	}
}
